<?php

namespace App\Tools;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 短信服务
 * Class SmsService
 */
class SmsService
{
    const SMS_CACHE_PREFIX = 'sms_code_cache_';
    const EXP_TIME = 300;
    CONST RES_TIME = 59;

    /**
     * 发送短信
     * @param $mobile
     * @param $code
     * @param $temp
     * @return array
     */
    public static function sendSms($mobile, $code, $temp = 'SMS_473810242') {
        // 调用 `send` 方法，设置签名、模板和参数
        return self::send($mobile, 'WF100', $temp, ['name' => '玩服壹百点西恩传奇抽奖平台']);
    }

    /**
     * 生成短信验证码
     * @param $mobile
     * @return array
     */
    public static function getCode($mobile)
    {
        $code = mt_rand(100000, 999999);
        $expire_time = self::EXP_TIME;
        $resend_time = self::RES_TIME;

        $codeInfo = cache()->get(self::SMS_CACHE_PREFIX . $mobile);
        if ($codeInfo) {
            if ($codeInfo['create_time'] + $resend_time > time()) {
                return [false, '短信发送过于频繁'];
            }
        }

        $data = [
            'code' => $code,
            'create_time' => time()
        ];
        cache()->set(self::SMS_CACHE_PREFIX . $mobile, $data, $expire_time);
        return [true, $code];
    }

    /**
     * 校验验证码
     * @param $mobile
     * @param $code
     * @return array
     */
    public static function checkCode($mobile, $code)
    {
        $codeInfo = cache()->get(self::SMS_CACHE_PREFIX . $mobile);
        if (!$codeInfo) {
            return [false, '验证码失效或已过期'];
        }

        if ($codeInfo['code'] != $code) {
            return [false, '验证码错误'];
        }

        cache()->set(self::SMS_CACHE_PREFIX . $mobile, null);
        return [true, ''];
    }

    /**
     * 发送短信的方法
     * @param $mobile
     * @param $signName
     * @param $temp
     * @param $param
     * @return array
     * @throws ClientException
     */
    public static function send($mobile, $signName, $temp, $param)
    {
        $config = config('ali'); // 从配置文件中读取AccessKey
        AlibabaCloud::accessKeyClient($config['AccessKeyID'], $config['AccessKeySecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $param_str = json_encode($param, JSON_UNESCAPED_UNICODE);

        try {
            // 发送短信
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => 'cn-hangzhou',
                        'PhoneNumbers' => $mobile,
                        'SignName' => $signName,  // 签名
                        'TemplateCode' => $temp,  // 模板代码
                        'TemplateParam' => $param_str  // 模板参数
                    ],
                ])
                ->request();
            return [true, $result->toArray()];  // 成功返回结果
        } catch (ClientException $e) {
            return [false, $e->getErrorMessage()];  // 客户端异常
        } catch (ServerException $e) {
            return [false, $e->getErrorMessage()];  // 服务器异常
        }
    }
}
